package forum.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import forum.bean.IntegrantesBean;

public class IntegrantesDAO implements Serializable {
	
	public boolean adicionar(IntegrantesBean integrantes) {
		try {
			this.removeAll();
			
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			Transaction transaction = session.beginTransaction();
			
			session.save(integrantes);
			
			transaction.commit();
			session.close();
			
			return true;
			
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}
	
	private void removeAll() {
		try {
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			Transaction transaction = session.beginTransaction();
			
			session.createSQLQuery("SELECT * FROM FORUM.SP_REMOVE_INTEGRANTES()")
				.list();
			
			transaction.commit();
			session.close();
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
	
	public IntegrantesBean get() {
		try {
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			
			List<IntegrantesBean> lista = session.getNamedQuery("integrantes").list();
			
			session.close();
			
			if (lista.size() > 0) {
				return lista.get(0);
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return null;
	}
}
